<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChRoomBroadcastSourceMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Model\ChRoomBroadcastSource;
use App\CustHub\Model\ChRoomMember;
use App\Setting\Service\SettingConfigService;
use Hyperf\Stringable\Str;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;

class RoomBroadcastSourceService extends AbstractService
{
    public $mapper;

    private ChRoomMapper $roomMapper;

    public function __construct(ChRoomBroadcastSourceMapper $mapper,ChRoomMapper $roomMapper)
    {
        $this->mapper = $mapper;
        $this->roomMapper = $roomMapper;
    }

    public function getPageList(?array $params = null, bool $isScope = false): array
    {
        if ($params['select'] ?? null) {
            $params['select'] = explode(',', $params['select']);
        }

        $params['pageSize'] = $params['page_size'] ?? 10;

        return $this->mapper->getPageList($params, $isScope);
    }

    /**
     * 新增数据源
     * @param array $data
     * @return bool
     */
    #[Transaction]
    public function saveSource(array $data): bool
    {
        if(!empty($data['room_id'])){
            $roomInfo = $this->roomMapper->findById($data['room_id']);
            $data['avatar'] = $roomInfo->room_avatar_url;
        }else{
            unset($data['room_id'],$data['listen_robot_id']);
        }

        $data['business_info'] = json_decode($data['business_info'], true);
        $data['speaker_ids'] = json_decode($data['speaker_ids'], true);


        if($data['type'] == 1){
            $ch_api_url = container()->get(SettingConfigService::class)->getConfigByKey("ch_api_url")['value'];
            $data['webhook_url'] = $ch_api_url.'/webhook/reply/'.Str::random(32);
        }


        $model = ChRoomBroadcastSource::create($data);
        if($model && !empty($data['share_account'])){
            $shareAccount = json_decode($data['share_account'],true);
            foreach ($shareAccount as $k=>$item){
                $shareAccount[$k] = (int)$item;
            }

            $model->shareAccount()->sync($shareAccount);
        }
        return true;
    }

    public function detail(array $params): \Hyperf\Database\Model\Model|ChRoomBroadcastSource|\Hyperf\Database\Model\Builder
    {
        $info = ChRoomBroadcastSource::query()
            ->with(['room'=>function ($query) {
                $query->select(['id','room_name','room_avatar_url']);
            },'robot'=> function ($query) {
                $query->select(['id','nickname','avatar']);
            }])
            ->where('id',$params['id'])
            ->first();

        if(empty($info)){
            throw new NormalStatusException('数据源不存在');
        }

        if(!empty($info->speaker_ids)){
            $speakerList = ChRoomMember::query()
                ->select(['id','nickname','avatar'])
                ->whereIn('id', $info->speaker_ids)
                ->get();
            $info->speaker_list = $speakerList;
        }else{
            $info->speaker_list = [];
        }

        $uids = $info->shareAccount()->pluck('id')->toArray();
        $info->share_account = $uids;
        $info->addHidden(['uid','main_uid','is_plat','created_at','updated_at']);
        return $info;
    }

    #[Transaction]
    public function updateSource(array $data): bool
    {
        $info = ChRoomBroadcastSource::query()->find($data['id']);
        if(empty($info)){
            throw new NormalStatusException('数据源不存在');
        }else{
            unset($data['room_id'],$data['listen_robot_id']);
        }

        if(!empty($data['room_id'])){
            $roomInfo = $this->roomMapper->findById($data['room_id']);
            $data['avatar'] = $roomInfo->room_avatar_url;
        }
       
        $data['business_info'] = json_decode($data['business_info'], true);
        $data['speaker_ids'] = json_decode($data['speaker_ids'], true);

        $rst = $this->mapper->update($info->id,  $data);
        if($rst){
            if(!empty($data['share_account'])){
                $shareAccount = json_decode($data['share_account'],true);
                $info->shareAccount()->sync($shareAccount);
            }else{
                $info->shareAccount()->exists() && $info->shareAccount()->detach();
            }

        }
        return $rst;
    }

    #[Transaction]
    public function deleteSource(array $data): bool
    {
        $info = ChRoomBroadcastSource::query()->find($data['id']);
        if(empty($info)){
            throw new NormalStatusException('数据源不存在');
        }

        $info->shareAccount()->detach();
        return $info->delete();
    }
}